const state = {
  sidebar: {
    opened: true,
    withoutAnimation: false
  },
  device: 'desktop',
  lastResizeTime: 0 // 新增：记录最后窗口变化时间（用于防抖）
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  UPDATE_RESIZE_TIME: (state) => {
    state.lastResizeTime = Date.now()
  }
}

const actions = {
  toggleSideBar ({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },

  closeSideBar ({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },

  toggleDevice ({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },

  init ({ commit }) {
    // 防抖处理（300ms内不重复触发）
    const handleResize = () => {
      const now = Date.now()
      if (now - state.lastResizeTime < 300) return

      commit('UPDATE_RESIZE_TIME', now)
      const isMobile = document.body.clientWidth < 768
      commit('TOGGLE_DEVICE', isMobile ? 'mobile' : 'desktop')
      if (isMobile) {
        commit('CLOSE_SIDEBAR', true)
      }
    }

    window.addEventListener('resize', handleResize)
    handleResize() // 初始化时立即执行一次

    // 返回清理函数
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }
}

const getters = {
  // 获取侧边栏是否打开的状态
  sidebarOpened: state => state.sidebar.opened,
  // 获取侧边栏是否无动画的状态
  sidebarWithoutAnimation: state => state.sidebar.withoutAnimation,
  // 获取设备类型
  deviceType: state => state.device,
  // 新增：响应式设备类型判断
  isMobile: state => state.device === 'mobile',
  isDesktop: state => state.device === 'desktop'
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
